<script setup lang="ts">
import {onMounted, ref} from "vue";
import {
  useAddOneAPI, useGetByIdAPI,
  useGetFirstLevelAPI, useGetParentByPidAPI,
  useGetSecondLevelAPI,
  useGetSecondLevelByPidAPI,
  useGetThirdLevelAPI, useUpdateByIdAPI
} from "@/apis/warehouseLayout.js";
import {ElMessage} from "element-plus";
import router from "@/router/index.js";
import {useRoute} from "vue-router";

const route=useRoute();
const warehouseLayoutId=route.params.id;



interface WarehouseLayout{
  containerNumber:string,
  containerName:string,
  pid:number,
  description:string
}
const warehouseLayout=ref<WarehouseLayout>({
  containerNumber:'',
  containerName:'',
  pid:0,
  description:''
})

const firstLevelList=ref<WarehouseLayout[]>([])
const secondLevelList=ref<WarehouseLayout[]>([])
const thirdLevelList=ref<WarehouseLayout[]>([])

const firstLevelIdList=ref<number[]>([]);
const secondLevelIdList=ref<number[]>([]);
const thirdLevelIdList=ref<number[]>([]);

const parentWarehouseLayout=ref<WarehouseLayout>()


// todo 这里，需要根据获取到的parentWarehouseLayout，在表单上显示出来*************************
onMounted(async ()=>{

  await useGetByIdAPI(Number(warehouseLayoutId)).then(res => {
    warehouseLayout.value = res.data
  })

  await useGetFirstLevelAPI().then(res => {
    firstLevelList.value = res.data;
    for (let i=0;i<firstLevelList.value.length;i++){
      firstLevelIdList.value.push(firstLevelList.value[i].id);
    }
  })
  await useGetSecondLevelAPI().then(res => {
    secondLevelList.value = res.data;
    for (let i=0;i<secondLevelList.value.length;i++){
      secondLevelIdList.value.push(secondLevelList.value[i].id);
    }

  })
  await useGetThirdLevelAPI().then(res => {
    thirdLevelList.value = res.data;
    for (let i=0;i<thirdLevelList.value.length;i++){
      thirdLevelIdList.value.push(thirdLevelList.value[i].id);
    }
  })

  if (firstLevelIdList.value.includes(warehouseLayout.value.id)){
    level.value="一级";
  }
  else if (secondLevelIdList.value.includes(warehouseLayout.value.id)){
    level.value="二级";
  }
  else if (thirdLevelIdList.value.includes(warehouseLayout.value.id)){
    level.value="三级";
  }


//   如果pid ！==0，说明是二级、三级菜单，需要获取到parentWarehouseLayout
  if (warehouseLayout.value.pid!==0) {
    //  通过Pid获取到父节点对象
    const res = await useGetParentByPidAPI(warehouseLayout.value.pid);
    parentWarehouseLayout.value=res.data;
    if (secondLevelIdList.value.includes(parentWarehouseLayout.value.id)){
      thirdLevelFlag.value=true;
      secondLevel.value=parentWarehouseLayout.value;
      showLevelList.value=[];
      const res= await useGetSecondLevelByPidAPI(parentWarehouseLayout.value.id)
      showLevelList.value=res.data;
    }
    else if (firstLevelIdList.value.includes(parentWarehouseLayout.value.id)){
      secondLevelFlag.value=true;
      firstLevel.value=parentWarehouseLayout.value;
      showLevelList.value=[];
      const res= await useGetSecondLevelByPidAPI(parentWarehouseLayout.value.id)
      showLevelList.value=res.data;
    }
  }
  else {
    showLevelList.value=firstLevelList.value;
  }
})

const disableSwitch=ref(false)

const updateSummit=async ()=>{

  // todo 这里需要判断，containerNumber是否重复的问题

  console.log(warehouseLayout.value);

  // todo，迟点打开下面语句
   await useUpdateByIdAPI(warehouseLayout.value).then(res=>{
     console.log(res.data);
     if (res.code===200){
       ElMessage({
         type:"success",
         message:res.msg
       })
       router.push("/manage/warehouseLayoutManager")
     }
     else {
       ElMessage({
         type:'error',
         message:res.msg
       })
     }
   })
}

const levelOptions = [
  {
    value: '1',
    label: '一级',
  },
  {
    value: '2',
    label: '二级',
  },
  {
    value: '3',
    label: '三级',
  },
]

const level=ref('');
const secondLevelFlag=ref(false);
const thirdLevelFlag=ref(false);

const firstLevel=ref({});
const secondLevel=ref({});

const showLevelList=ref<any>();

// 定义获取 containerNumber 最大值的函数
const getMaxContainerNumber = (list:[]) => {
  if (list.length === 0) {
    return 0;
  }
  // 遍历 firstLevelList，将 containerNumber 转换为数字并找出最大值
  return Math.max(...list.map(item => Number(item.containerNumber)));
};


const levelSelectChange= (val:any)=>{
  showLevelList.value=[];
  if (val.value==='1'){
    secondLevelFlag.value=false;
    thirdLevelFlag.value=false;
    warehouseLayout.value.pid=0;
    showLevelList.value=firstLevelList.value;

    warehouseLayout.value.containerNumber=(getMaxContainerNumber(firstLevelList.value)+1).toString();
  }
  else if (val.value==='2'){
    secondLevelFlag.value=true;
    thirdLevelFlag.value=false;
  }
  else if (val.value==='3'){
    secondLevelFlag.value=false;
    thirdLevelFlag.value=true;
    warehouseLayout.value.pid=secondLevel.value.id;
  }
}

// 添加二级节点
const secondSelectChange=async (val:any)=>{
  showLevelList.value=[];
  const res= await useGetSecondLevelByPidAPI(val.id)
  showLevelList.value=res.data;
  const secondList=res.data;
  if (secondList===null){
    warehouseLayout.value.containerNumber="1";
    warehouseLayout.value.pid=val.id;
  }
  else {
    let maxNum= getMaxContainerNumber(secondList)+1;
    console.log(maxNum);
    warehouseLayout.value.containerNumber=maxNum.toString();
    warehouseLayout.value.pid=val.id;
  }

}

// 添加三级节点
const thirdSelectChange=async (val:any)=>{
  showLevelList.value=[];
  const res= await useGetSecondLevelByPidAPI(val.id)
  const thirdList=res.data;
  showLevelList.value=res.data;
  if (thirdList===null){
    warehouseLayout.value.containerNumber="1";
    warehouseLayout.value.pid=val.id;
  }else {
    let maxNum= getMaxContainerNumber(thirdList)+1;
    warehouseLayout.value.containerNumber=maxNum.toString();
    warehouseLayout.value.pid=val.id;
  }
}




</script>

<template>

  <!-- 面包屑 -->
  <div class="bread-container">
    <el-breadcrumb separator=">">
      <el-breadcrumb-item :to="{ path: `/` }">首页</el-breadcrumb-item>
      <el-breadcrumb-item :to="{path:`/manage/warehouseLayoutManager`}" >货架列表</el-breadcrumb-item>
      <el-breadcrumb-item  >修改货架</el-breadcrumb-item>
    </el-breadcrumb>
  </div>

  <div class="divTable">
    <table class="table">
      <tbody>
      <tr>
        <td class="tableTitle" colspan="4" >修改货架数据</td>
      </tr>
      <tr>
        <td style="width: 250px;height: 15px;text-align: center;background: #EFF6FF;color: #242424;font-family: 微软雅黑,serif">货架名称</td>
        <td style="width: 350px;height: 15px;   text-align: center  "><el-input  v-model="warehouseLayout.containerName" />
        </td>
        <td style="width: 250px;height: 15px; text-align: center ;background: #EFF6FF"  >准备修改货架层级</td>
        <td style="width: 350px;height: 15px ; text-align: center">
          <el-select
              :key="level"
              v-model="level"
              placeholder="Select"
              size="large"
              @change="levelSelectChange"
          >
            <el-option
                v-for="item in levelOptions"
                :key="item.value"
                :label="item.label"
                :value="item"
            />
          </el-select>
        </td>
      </tr>

      <!--      如果level选中的是二级节点，那么这个这行显示，下面这行不显示-->
      <tr v-if="secondLevelFlag">
        <td style="width: 250px;height: 15px;text-align: center;background: #EFF6FF">请选择一级货架名称</td>
        <td colspan="3" style="width: 350px;height: 15px;text-align: center  ">
          <el-select
              value-key="id"
              v-model="firstLevel"
              placeholder="Select"
              size="large"
              @change="secondSelectChange"
          >
            <el-option
                v-for="item in firstLevelList"
                :key="item.id"
                :label="item.containerName"
                :value="item"
            />
          </el-select>


        </td>
      </tr>
      <!--      如果选中的是三级节点，那么这行显示上面这行不显示-->
      <tr v-if="thirdLevelFlag">
        <td style="width: 250px;height: 15px;text-align: center;background: #EFF6FF">请选择二级货架名称</td>
        <td colspan="3" style="width: 350px;height: 15px;text-align: center  ">
          <el-select
              value-key="id"
              v-model="secondLevel"
              placeholder="Select"
              size="large"
              @change="thirdSelectChange"
          >
            <el-option
                v-for="item in secondLevelList"
                :key="item.id"
                :label="item.containerName"
                :value="item"
            />
          </el-select>
        </td>
      </tr>
      <tr>
        <td style="width: 250px;height: 15px;text-align: center ;background: #EFF6FF"  >货架描述</td>
        <td colspan="3" style="width: 350px;height: 15px;text-align: center   "><el-input type="textarea" v-model="warehouseLayout.description"/></td>
      </tr>
      <tr>
        <td colspan="4" style="background:#EFF6FF ">
          <el-button @click="updateSummit" type="primary" :disabled="disableSwitch" style="margin-top: 1%;margin-bottom: 1%" >确认修改</el-button>
        </td>
      </tr>

      <tr>
        <td style="width: 250px;height: 15px;text-align: center ;background: #EFF6FF"  >填写货架名称是否要注意，不要使用已存在的货架名</td>
        <td colspan="3" style="width: 350px;height: 15px;text-align: center   "><div align="left" v-for="item in showLevelList">货架名称：{{item.containerName}}</div></td>
      </tr>

      </tbody>
    </table>
  </div>


</template>

<style scoped lang="scss">
.bread-container {
  padding: 25px 10px;
  margin-left: 10px;
}


.divTable {
  position: static;
  top: 150px;
  bottom: 0;
  left: 300px;
  right: 0;
  margin: auto;
}


table, td,tr{
  border: 1px solid #44a8da;
  text-align: center;
  border-spacing: 0;
  border-collapse: collapse;
  height: 45px;
}

.tableTitle{

  border-right: 0 none;
  border-left: 0 none;
  text-align: center;
  font-size: large;
  font-weight: bold;
}

.demo-image__error .image-slot {
  font-size: 30px;
}
.demo-image__error .image-slot .el-icon {
  font-size: 30px;
}
.demo-image__error .el-image {
  width: 100%;
  height: 200px;
}

.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>